package studyguide.ch14;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class HttpMidlet extends MIDlet {

	private final Command openCommand;
	private final Command exitCommand;
	private final Display display;
	
	private final Form mainForm;
	private final TextField urlField;
	private final StringItem indicator;
	private final TextField contentsField;
	
	
	private class SampleCommandListener implements CommandListener {
		public void commandAction(Command command, Displayable displayable) {
			if (command == exitCommand) {
				destroyApp(true);
				notifyDestroyed();
			} else if (command == openCommand) {
				// Runs network communications on a separate thread
				indicator.setText("waiting...");
				contentsField.setString("");
				Thread thread = new Thread(new NetworkCommunication());
				thread.start();
			} else {
				throw new RuntimeException("UNKNOWN COMMAND" + command);
			}
		}
	}
	
	private class NetworkCommunication implements Runnable {
		public void run() {
			HttpConnection connection = null;
			try {
				connection = (HttpConnection) Connector.open(urlField.getString());
				// Nothing to do on setup state. go to connected state:
				int responseCode = connection.getResponseCode();
				if (responseCode >= 200 && responseCode <= 300) {
					// Success
					Reader reader = new InputStreamReader(connection.openInputStream());
					int read = reader.read();
					StringBuffer buffer = new StringBuffer();
					while (read != -1) {
						char ch = (char) read;
						buffer.append(ch);
						read = reader.read();
					}
					contentsField.setString(buffer.toString());
				} else {
					// HTTP error:
					contentsField.setString("Error code:" + responseCode + "[" + connection.getResponseMessage() + "]");
				}
				indicator.setText("stopped");
			} catch (Exception e) {
				indicator.setText("Error:" + e);
			} finally {
				if (connection != null) {
					try {
						connection.close();
					} catch (IOException e) {
						indicator.setText("Error:" + e.getMessage());
					}
				}
			}
		}
	}
	
	public HttpMidlet() throws IOException {
		mainForm = new Form("Http Sample");
		exitCommand = new Command("Exit", Command.EXIT, 1);
		openCommand = new Command("Open", Command.SCREEN, 1);
		
		mainForm.addCommand(openCommand);
		mainForm.addCommand(exitCommand);
		
		SampleCommandListener listener = new SampleCommandListener();
		mainForm.setCommandListener(listener);
		display = Display.getDisplay(this);
		
		urlField = new TextField("URL:", "http://localhost:8080/JavaMEStudyGuide-Web/page.html", 100, TextField.ANY);
		contentsField = new TextField("Contents:", "", 1000, TextField.ANY);
		
		indicator = new StringItem("Status:", "stopped");
		
		mainForm.append(urlField);
		mainForm.append(indicator);
		mainForm.append(contentsField);
	}
	
	protected void destroyApp(boolean unconditional) {
	}

	protected void pauseApp() {
	}

	protected void startApp() throws MIDletStateChangeException {
		display.setCurrent(mainForm);
	}

}
